package com.vendar.quicknote;

import com.vendar.quicknote.R;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SendMessageActivity extends Activity implements OnClickListener{
	private EditText mEditor = null;
	private Button mSendBtn = null;
	private EditText mReceiver = null;
	private long mNoteId = -1;
	
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.send_message);
		Setup();
	}
	
	private void Setup(){
		mEditor = (EditText)findViewById(R.id.editor);
		mSendBtn = (Button)findViewById(R.id.sendBtn);
		mReceiver = (EditText)findViewById(R.id.recipient);
		
		if( getIntent() == null ) return ;
		Bundle args = getIntent().getExtras();
		if( args == null ) return ;
		
		String content = args.getString("content");
		mNoteId = args.getLong("id");
		if( content == null ) return ;
		mEditor.setText(content);
		
		//setup event handlers
		mSendBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if( v==mSendBtn ){
			//check variables
			String receiver = mReceiver.getText().toString();
			String content = mEditor.getText().toString();
			if( receiver == null || receiver.length() < 1 ){
				Toast.makeText(this, R.string.recipient_cannot_be_null, 500).show();
				return ;
			}
			if( content == null || receiver.length() < 1 ){
				Toast.makeText(this, R.string.content_cannot_be_null, 500).show();
				return ;
			}
			
			//send message
			PendingIntent pintent = PendingIntent.getBroadcast(this, 0, new Intent(), 0);
			SmsManager sms = SmsManager.getDefault();
			try{
				sms.sendTextMessage(receiver, null, content, pintent, null);
			}catch( Exception e ){
				Toast.makeText(this, R.string.send_message_failed, 500);
				return ;
			}
			
			//check if we succeed!
			boolean res = true;
			if( !res ){
				Toast.makeText(this, R.string.send_message_failed, 500).show();
				return ;
			}
			
			Toast.makeText(this, R.string.send_message_succeed, 500).show();
			
			//go back to start activity
			Intent intent = new Intent();
			Bundle args = new Bundle();
			args.putLong("id", mNoteId);
			args.putString("note", content);//note has been changed
			intent.putExtras(args);
			this.setResult(RESULT_OK,intent);
			this.finish();
		}
	}
}
